package cn.stronglink.asset.message.mq.dam.handle;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.stronglink.asset.message.mq.dam.entity.IScreenCommandFactory;
import cn.stronglink.asset.message.mq.dam.entity.ScreenCommandEntity;
import cn.stronglink.asset.message.mq.dam.entity.SensorOfAwsPostdataEntity;
import cn.stronglink.asset.message.mq.dam.entity.SensorParamesEntity;
import cn.stronglink.asset.message.mq.dam.entity.dacai.UpdateArrayTextCommandFactory;
import cn.stronglink.asset.message.mq.dam.message.MQMessageOfDAM;
import cn.stronglink.asset.message.mq.topic.ReaderInfoSender;
import cn.stronglink.asset.module.dam.service.IDamService;
import cn.stronglink.asset.module.dam.service.DamService;
import cn.stronglink.suite.core.util.ContextUtils;

/**
 * 实时传感器消息的处理
 * 
 * @author yuzhantao
 *
 */
public class RealtimeSensorDatasHandle extends AbstractReturnExceptionHandle {
	private final static String SENSOR_SPAN_FLAG="/";	// 传感器间隔的标识符
	private final static int MAX_SENSOR_SHOW_COUNT=6;	// 最大传感器显示数量
	protected final static String TOPIC_NAME = "serviceToDam";
	protected final static String ACTION_CODE = "realTimeDatas";
	protected final static String SEND_ACTION_CODE = "screenCommand";
	protected final static short SCREEN_ID = 1;
	protected IDamService sensorService = (DamService)ContextUtils.getBean("sensorService");
	private ReaderInfoSender topicSender = (ReaderInfoSender) ContextUtils.getBean("readerInfoSender");
	@Override
	public boolean isHandle(MQMessageOfDAM msg) {
		if (msg.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void handleMessage(MQMessageOfDAM msg) {
		SensorOfAwsPostdataEntity sap = ((JSONObject)msg.getAwsPostdata()).toJavaObject(SensorOfAwsPostdataEntity.class);
		
		// 发送温湿度信息到屏幕
		try {
			this.sendSensorData2Screen(sap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 保存温湿度信息到数据库
		this.saveSensorData2DB(sap);
	}
	
	/**
	 * 发送温湿度信息到屏幕
	 * @param sap
	 * @throws Exception
	 */
	private void sendSensorData2Screen(SensorOfAwsPostdataEntity sap) throws Exception {
		Map<Short,String> sensorMap = new HashMap<>();
		for(int i=0;i<Math.min(sap.getSensorList().size(),MAX_SENSOR_SHOW_COUNT);i++) {
			SensorParamesEntity sp = sap.getSensorList().get(i);
			String sensorDatas = this.getSensorShowContent(sp);
			short sensorKey = (short)sp.getSensorPosition();
			if(sensorMap.containsKey(sensorKey)) {
				String oldSensorDatas = sensorMap.get(sensorKey);
				if(sp.getSensorType()==1) { // 如果是温度传感器将数值放前面
					sensorMap.put(sensorKey,sensorDatas + SENSOR_SPAN_FLAG + oldSensorDatas);
				}else if(sp.getSensorType()==2) {  // 如果是湿度传感器，将数值放后面
					sensorMap.put(sensorKey,oldSensorDatas + SENSOR_SPAN_FLAG + sensorDatas);
				}else { // 未知传感器或门直接赋值
					sensorMap.put((short)sp.getSensorPosition(), sensorDatas);
				}
			}else {
				sensorMap.put((short)sp.getSensorPosition(), sensorDatas);
			}
		}
		
		// 更新时间
		SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");   
		String date=sDateFormat.format(new Date());
		sensorMap.put((short)8, date);
		
		IScreenCommandFactory factory = new UpdateArrayTextCommandFactory(sap.getRackConverCode(),SCREEN_ID,sensorMap);
		ScreenCommandEntity sc = factory.createScreenCommand();
		
		MQMessageOfDAM message = new MQMessageOfDAM();
		message.setActioncode(SEND_ACTION_CODE);
		message.setAwsPostdata(sc);
		message.setTimestamp(System.currentTimeMillis());
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME,json);
		logger.info("发送温湿度命令:{}",json);
	}
	
	/**
	 * 获取传感器显示的内容
	 * @param sp
	 * @return
	 */
	private String getSensorShowContent(SensorParamesEntity sp) {
		String sensorContent="";  // 传感器显示的内容
		switch(sp.getSensorType()) {
		case 1:  	// 温度
			sensorContent=sp.getSensorDatas()+"℃";
			break;
		case 2:  	// 湿度
			sensorContent=sp.getSensorDatas()+"RH";
			break;
		case 3:		// 门
			sensorContent=(int)sp.getSensorDatas()==0?"关":"开";
			break;
		}
		
		return sensorContent;
	}
	
	/**
	 * 保存温湿度信息到数据库
	 * @param sap
	 */
	private void saveSensorData2DB(SensorOfAwsPostdataEntity sap) {
		for(int i=0;i<sap.getSensorList().size();i++) {
			SensorParamesEntity sensor = sap.getSensorList().get(i);
			sensorService.replaceSensorInfo(sap.getRackConverCode(), 
					sensor.getSensorPosition(), 
					sensor.getSensorType(), 
					0, (int)sensor.getSensorDatas());
		}
	}
}
